<template>
 <div class="container">
    <div class="card-search">
        <el-form size="small" :inline="true" label-width="60px" :model="form">
            <el-form-item label="角色名">
            <el-input size="small" v-model="form.name" placeholder="请输入角色名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="getAllData">查询</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="card-table">
        <el-button style="margin-bottom:12px;" type="primary" icon="el-icon-plus" size="medium" @click="title='增加用户',dialogTableVisible=true">新增</el-button>
        <el-table
        :header-cell-style="getRowClass"
        :data="tableData"
        style="width: 100%">
        <el-table-column
            prop="name"
            label="角色名称">
        </el-table-column>
        <el-table-column
            prop="code"
            label="权限类型">
        </el-table-column>
        <el-table-column
            prop="desc"
            label="描述">
        </el-table-column>
        <el-table-column
            fixed="right"
            prop="prop"
            label="操作">
            <template slot-scope="{ row }">
                <el-button style="padding:0;color:#4D70FF;" class="btnText" size="medium" type="text" icon="el-icon-setting" @click="openDrawer(row)">设置权限</el-button>
                <el-button style="padding:0;color:#4D70FF;" class="btnText" size="medium" type="text" icon="el-icon-edit-outline" @click="title='修改用户',ruleForm={...row},dialogTableVisible=true">编辑</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="pagin" v-if="total>=pageSize">
            <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogTableVisible" :modal-append-to-body="false">
        <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-dynamic">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="权限类型" prop="code">
                <el-input :disabled="title === '修改用户'?true:false" v-model="ruleForm.code"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="desc">
                <el-input v-model="ruleForm.desc"></el-input>
            </el-form-item>
            <el-form-item class="dialog-footer dfooter">
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 抽屉 -->
    <el-drawer
        size="40%"
        :visible.sync="drawer"
        :with-header="false"
        :modal-append-to-body="false"
        class="drawerClass">
        <el-tabs @tab-click="handleClick" style="height:100%;" v-model="activeName" type="border-card">
        <el-tab-pane :lazy="true" label="角色api" name="first">
            <div class="btnclasss">
                <el-button style="margin:12px;" type="primary" @click="saveApi()">保存</el-button>
            </div>
            <div class="treeClass">
            <el-tree
                :data="apiTree"
                show-checkbox
                node-key="_id"
                ref="apiTree"
                default-expand-all
                accordion
                :highlight-current="true"
                :props="defaultPropsApi">
            </el-tree>
            </div>
        </el-tab-pane>
        <el-tab-pane label="角色菜单" name="second">
            <el-alert
                :closable="false"
                show-icon
                style="margin-bottom:12px;"
                title="注:请通过拖动树型结构的分支实现角色页面的配置"
                type="warning">
            </el-alert>
            <div class="btnclasss">
                <el-button style="margin:12px;" @click="saveRoutes" type="primary">保存</el-button>
            </div>
            <el-tree
                :default-expanded-keys="getExpandedKeysRoutes"
                :data="routesTree"
                show-checkbox
                node-key="path"
                ref="routesTree"
                draggable
                :highlight-current="true"
                :props="defaultPropRoutes"
                :allow-drop="allowDrop"
                :allow-drag="allowDrag">
                <div style="font-size:14px;" slot-scope="{node}">
                  {{node.data.name}}
                  <span style="color:#999;" v-if="node.data.hidden">
                  (隐藏)
                  </span>
                  <span
                  :class="ruleForm.firstPage===node.data.path?'firstPage_style':'firstPage_style-not'"
                  @click.prevent.stop="handleFirstPage(node.data.path)"
                  v-if="node.data.children === undefined && !node.data.hidden">
                      {{ruleForm.firstPage===node.data.path?'首页':'设为首页'}}
                  </span>
                </div>
            </el-tree>
        </el-tab-pane>
        </el-tabs>
    </el-drawer>
 </div>
</template>

<script>
import { showRoleTable, newRole, updateRole } from '@/api/auth/roleApi.js'
import { showApiTable } from '@/api/auth/apiApi.js'
import roles from '@/utils/roles.js'
export default {
  name: 'test',
  components: {},
  data () {
    return {
      form: {
        name: ''
      },
      ruleForm: {
        name: '',
        code: '',
        desc: '',
        apis: [],
        roleRoutes: '',
        firstPage: '/repertory'
      },
      selectRow: {},
      tableData: [],
      pageSize: 10,
      currPage: 1,
      total: 1,
      dialogTableVisible: false,
      title: '',
      drawer: false,
      apiTree: [],
      routesTree: roles['测试管理员权限'],
      getExpandedKeysRoutes: [], // 树型结构默认展开的节点数组
      activeName: 'first', // 树型结构设置tabs首次进入的标签页
      //   firstPage: '/repertory', // 树型结构设置默认首页
      defaultPropsApi: {
        children: 'children',
        label: 'name'
      },
      defaultPropRoutes: { // 树型结构设置默认绑定值
        children: 'children',
        label: 'name'
      },
      rules: {
        name: [
          { required: true, message: '请填写角色名', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请填写角色Id', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请填写描述', trigger: 'change' }
        ]
      }
    }
  },
  computed: {},
  watch: { },
  created () {},
  mounted () {
    this.getApis()
    this.getAllData()
  },
  methods: {
    getAllData () {
      const para = {
        name: this.form.name,
        pageSize: this.pageSize,
        currPage: this.currPage
      }
      showRoleTable(para).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.pageData || []
          this.total = res.data.data.total
        }
      })
    },
    getApis () {
      showApiTable().then(res => {
        console.log(res.data.data)
        const tree = { GET: [], POST: [], PUT: [], DELETE: [] }
        const data = res.data.data.pageData
        for (let i = 0; i < data.length; i++) {
          const each = data[i]
          tree[each.method].push(each)
        }
        for (var key in tree) {
          this.apiTree.push({ name: key, id: key, children: tree[key] })
        }
      })
    },
    // 提交填写或修改信息
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '增加用户') {
            this.handleSetNewRole(this.ruleForm)
          } else {
            this.handleUpdateRole(this.ruleForm, '修改成功')
          }
          this.dialogTableVisible = false
        } else {
          console.log('error!')
          return false
        }
      })
    },
    handleSetNewRole (payload) {
      newRole(payload).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '创建成功',
            type: 'success'
          })
          this.dialogTableVisible = false
        } else {
          this.$message({
            message: res.data.message,
            type: 'warning'
          })
        }
        this.getAllData()
      })
    },
    // 提交角色api
    saveApi () {
    //   console.log(this.$refs.apiTree.getCheckedNodes())
      const getNodes = this.$refs.apiTree.getCheckedNodes()
      const apis = []
      for (let index = 0; index < getNodes.length; index++) {
        const each = getNodes[index]
        if (each.children === undefined) {
          apis.push(each._id)
        }
      }
      const payload = {
        ...this.selectRow,
        apis: apis
      }
      console.log(payload)
      this.handleUpdateRole(payload, 'api权限设置成功')
    },
    // 提交角色页面
    saveRoutes () {
      const routes = this.getSubmitRoutes()
      const payload = {
        ...this.selectRow,
        firstPage: this.ruleForm.firstPage,
        roleRoutes: JSON.stringify(routes)
      }
      console.log(payload)
      this.handleUpdateRole(payload, '角色菜单设置成功')
    },
    handleUpdateRole (payload, message) {
      updateRole(payload).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: message,
            type: 'success'
          })
          this.dialogTableVisible = false
        } else {
          this.$message({
            message: res.data.message,
            type: 'warning'
          })
        }
        this.getAllData()
      })
    },
    // 打开抽屉设置api和页面
    openDrawer (row) {
      this.selectRow = { ...row }
      this.ruleForm = { ...row }
      const selectkeys = row.apis
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.apiTree.setCheckedKeys(selectkeys)
        this.clickAllNode_menu()
      })
    },
    // 树型结构提交角色菜单
    getSubmitRoutes () {
      const checkedKeys = this.$refs.routesTree.getCheckedKeys().toString()
      function fun (params) {
        const getmap = params.map(each => {
          const check = checkedKeys.indexOf(each.path) > -1
          if (each.children && each.children !== undefined && each.permissions === undefined) {
            const getChildren = fun(each.children)
            if (getChildren.length === 0) return
            return { name: each.name, path: each.path, icon: each.icon, permissions: each.permissions, children: getChildren }
          } else if (check) {
            return { name: each.name, path: each.path, icon: each.icon, permissions: each.permissions, hidden: each.hidden }
          }
        }).filter(item => typeof item !== 'undefined')
        return getmap
      }
      const newMenus = fun(roles['测试管理员权限'])
      console.log('newMenus', newMenus)
      return newMenus
    },
    // 树型结构点击角色菜单时选中项目
    handleClick (tab, event) {
    //   if (tab.name === 'second') {
    //     this.$nextTick(() => {
    //     })
    //   }
    },
    // 树型结构不可以拖入的目标项目
    allowDrop (raggingNode, dropNode, type) {
      const allowDrop1 = dropNode.data.permissions !== undefined
      if (allowDrop1) {
        return type !== 'inner'
      } else {
        return true
      }
    },
    // 树型结构不可以拖动的项目
    allowDrag (draggingNode) {
      const draggable = draggingNode.data.hidden !== true
      return draggable
    },
    // 树型结构产生选中菜单的数组
    clickAllNode_menu () {
      if (!this.selectRow.roleRoutes || this.selectRow.roleRoutes === '') {
        this.$refs.routesTree.setCheckedKeys([])
        return
      }
      const allRoles = JSON.parse(this.selectRow.roleRoutes || { kong: 'kong' })
      var checkedKeys = []
      var expendKeys = []
      function getRoles (params) {
        params.map(each => {
          if (each.permissions === undefined) {
            expendKeys.push(each.path)
          }
          if (each.children !== undefined) {
            getRoles(each.children)
          } else {
            checkedKeys.push(each.path)
          }
        })
      }
      getRoles(allRoles)
      this.getExpandedKeysRoutes = expendKeys
      this.$refs.routesTree.setCheckedKeys(checkedKeys)
    },
    // 树型结构设置首页
    handleFirstPage (path) {
      this.ruleForm.firstPage = path// 需要注释
      const payload = {
        ...this.selectRow,
        firstPage: path
      }
      this.handleUpdateRole(payload, '首页设置成功')
      console.log(payload)
    //   this.$message({
    //     message: '首页设置成功',
    //     type: 'success'
    //   })
    },
    resetForm (formName) {
      this.dialogTableVisible = false
      this.$refs[formName].resetFields()
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getAllData()
    },
    handleCurrentChange (val) {
      this.currPage = val
      this.getAllData()
    }
  }
}
</script>

<style  scoped>
 .el-dialog__header{
    border-bottom: thin solid rgb(229, 229, 236);
}
.el-alert--warning.is-light {
    background-color: #fbf5ed;
    color: #ff8800 !important;
}
.firstPage_style{
  color:$warning;
  &-not{
    color: $primary;
  }
}
</style>
